package com.pmes.controller;


import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.pmes.Constant;
import com.pmes.model.User;
import com.pmes.service.UserService;
import com.pmes.utils.JsonUtil;
import com.pmes.utils.RequestUtil;
import com.pmes.utils.SessionUtil;

/**
 * 用户登陆控制器
 */
@Controller
public class LoginController {

	private static String validateResult = "出错了";
	
	@Resource
	private UserService userService;
	
	private Map<String,Integer> errorTime = new HashMap<String,Integer>();
	@RequestMapping(value = "/login.do")
	public String doService(HttpServletRequest request, HttpServletResponse response) throws Exception{
		User userInfo = new User();
		userInfo.setUserId(request.getParameter("userId"));
		userInfo.setUserPassWd(request.getParameter("userPassWd"));
		userInfo.setSessionId(request.getSession(false).getId());
		userInfo.setSessionTime(System.currentTimeMillis());
		Map<String, Object> map = new HashMap<String,Object>();
		map.put("success", false);
       	map.put("message", validateResult);
		response.setContentType("text/json;charset=UTF-8");
	    String imgCode=RequestUtil.getString(request, Constant.IMAGE_CODE);
	    /*if(!SessionUtil.isVerCode(request, imgCode)) {
			response.getWriter().print(JsonUtil.jsonOut(map));
			return null;
	    }*/
	    User user2 = userService.getUserByLogin(userInfo);
        if (!user2.getUserId().equals(userInfo.getUserId()) ) {
			response.getWriter().print(JsonUtil.jsonOut(map));
			return null;
		}
        String ip = getIpAddr(request);
        Integer times = errorTime.get(ip);
        if(times != null && times >= 5){
			response.getWriter().print(JsonUtil.jsonOut(map));
			return null;
        }
        
		if (!user2.getUserPassWd().equals(userInfo.getUserPassWd()) ) {
			if(times == null){
				errorTime.put(ip, 1);
			}else{
				errorTime.put(ip, times + 1);
			}
			response.getWriter().print(JsonUtil.jsonOut(map));
			return null;
		}
		if(errorTime.containsKey(ip)){
			errorTime.remove(ip);
		}
		String url = "MyIndex.do?userId=" + userInfo.getUserId();
       	map.put("success", true);
       	map.put("message", url);
		response.getWriter().print(JsonUtil.jsonOut(map));
		return null;
	}
	
	@RequestMapping(value = "/MyIndex.do")
	public ModelAndView clientManageService(HttpServletRequest request, HttpServletResponse response) throws Exception{
		String userId = request.getParameter("userId");
		String sessionId = request.getSession(false).getId();
		ModelAndView model = null;
		model = new ModelAndView("forward:ClientManage.jsp");
		return model;
	}

	public static String getIpAddr(HttpServletRequest request) {
		if (request == null) {
			return "unknown";
		}
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("X-Forwarded-For");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("X-Real-IP");
		}

		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}
}
